import os
from openslide import OpenSlide, OpenSlideError
import argparse


def test_svs_directory(folder_path, recursive=True):
    """
    测试文件夹中所有 .svs 文件是否可以被 OpenSlide 打开

    Parameters:
        folder_path (str): 目标文件夹路径
        recursive (bool): 是否递归搜索子文件夹
    """
    if not os.path.exists(folder_path):
        print(f"❌ Error: Folder does not exist: {folder_path}")
        return

    # 获取所有 .svs 文件
    svs_files = []
    for root, dirs, files in os.walk(folder_path):
        for file in files:
            if file.lower().endswith(".svs"):
                svs_files.append(os.path.join(root, file))
        if not recursive:
            break  # 只遍历当前目录

    if not svs_files:
        print(f"🔍 No .svs files found in {folder_path}")
        return

    print(f"🔍 Found {len(svs_files)} .svs files. Testing...\n")

    successful = []
    failed = []

    for file_path in svs_files:
        try:
            with OpenSlide(file_path) as slide:
                # 可选：读取一些基本信息
                level_count = slide.level_count
                dims = slide.dimensions
                print(f"✅ OK: {file_path} (Levels: {level_count}, Size: {dims})")
                successful.append(file_path)
        except OpenSlideError as e:
            print(f"❌ FAILED: {file_path}")
            print(f"   Error: {e}")
            failed.append((file_path, str(e)))
        except Exception as e:
            print(f"❌ UNKNOWN ERROR: {file_path}")
            print(f"   Exception: {type(e).__name__}: {e}")
            failed.append((file_path, f"{type(e).__name__}: {e}"))

    # 总结
    print("\n" + "=" * 60)
    print("📊 SUMMARY")
    print("=" * 60)
    print(f"Total files tested: {len(svs_files)}")
    print(f"✅ Successfully opened: {len(successful)}")
    print(f"❌ Failed to open: {len(failed)}")

    if failed:
        print("\nThe following files failed:")
        for file_path, error in failed:
            print(f"  - {file_path}")
            print(f"    Error: {error}")


if __name__ == "__main__":
    parser = argparse.ArgumentParser(
        description="Test if all .svs files in a folder can be opened by OpenSlide."
    )
    parser.add_argument(
        "--folder",
        default="/data0/lcy/slide_tmp",
        help="Path to the folder containing .svs files",
    )
    parser.add_argument(
        "--no-recursive",
        default = False ,action="store_true",
        help="Do not search subdirectories",
    )

    args = parser.parse_args()

    test_svs_directory(args.folder, recursive=not args.no_recursive)
